﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Raven.Client.Linq;

namespace OpenWaves.ActivityFeed.RavenDB
{
    public static class UpdateExtensions
    {
        public static IQueryable<Update> ForSubscriber(this IQueryable<Update> query, Subscriber subscriber)
        {
            Contract.Requires<ArgumentNullException>(subscriber != null);

            var followedTopics = subscriber.Subscriptions;
            query = query.Where(update => update.PublishedBy == subscriber.Id || update.Topics.Any(t => t.In(followedTopics)));

            return query;
        }

        public static IQueryable<Update> FilterByTopics(this IQueryable<Update> query, params Topic[] topics)
        {
            Contract.Requires<ArgumentNullException>(topics != null);

            return query.FilterByTopics(topics.AsEnumerable());
        }

        public static IQueryable<Update> FilterByTopics(this IQueryable<Update> query, IEnumerable<Topic> topics)
        {
            Contract.Requires<ArgumentNullException>(topics != null);

            if (topics.Any() == false)
                return query;
            
            return query.Where(u => u.Topics.Any(t => t.In(topics)));
        }

        public static IQueryable<Update> SecurityTrim(this IQueryable<Update> query, IEnumerable<UserGroup> userGroups)
        {
            Contract.Requires<ArgumentNullException>(userGroups != null);

            return query.Where(u => u.IsPublic || u.UserGroups.Any(r => r.In(userGroups)));
        }       
    }
}